package com.netty.httpserver;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class NettyServer {

	public static void main(String[] args) {
		NettyServer.start(8080);
	}

	private static void start(int port) {
		long starttime = System.currentTimeMillis();
		EventLoopGroup boss = new NioEventLoopGroup();
		EventLoopGroup workers = new NioEventLoopGroup();

		ServerBootstrap server = new ServerBootstrap();
		server.group(boss, workers);

		try { 
			server.channel(NioServerSocketChannel.class)
			.childHandler(new MyChannelInitializer())  // 自定义初始化
			.option(ChannelOption.SO_BACKLOG, 128)
			.childOption(ChannelOption.SO_KEEPALIVE, true);

			ChannelFuture fu = server.bind(port).sync();
			
			long startedtime = System.currentTimeMillis();
			System.out.println("服务器启动成功，端口：" + port + " 耗时：" + (startedtime - starttime));

			fu.channel().closeFuture().sync();

		} catch (InterruptedException e) {
			boss.shutdownGracefully();
			workers.shutdownGracefully();
		}

	}

}
